package com.xsm.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.deploy.net.HttpResponse;
import com.xsm.yygh.cmn.listener.DictListener;
import com.xsm.yygh.cmn.mapper.DictMapper;
import com.xsm.yygh.cmn.service.DictService;
import com.xsm.yygh.model.cmn.Dict;

import com.xsm.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Override
    public List<Dict> selectAllDict(Long id) {

        QueryWrapper<Dict> qw = new QueryWrapper<>();

        qw.eq("parent_id", id);

        List<Dict> dictList = baseMapper.selectList(qw);

        for(Dict d: dictList){
            d.setHasChildren(this.hadChild(d.getId()));
        }

        return dictList;
    }


    @Override
    public void exportDict(HttpServletResponse response) {

        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");

        // 查询数据
        List<Dict> dictList = baseMapper.selectList(null);

        List<DictEeVo> export = new ArrayList<>();

        for(Dict d: dictList){
            DictEeVo obj = new DictEeVo();

            // obj.setId(d.getId());
            BeanUtils.copyProperties(d, obj);

            export.add(obj);
        }

        // 下载
        try {
            // 设置对照：DictEeVo.class
            // 单元名称： sheet
            // 下载数据： doWrite
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("工作表1")
                    .doWrite(export);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void uploading(MultipartFile file) {

        try {
            /*
              file.getInputStream()    输入流
              DictEeVo.class       对照表
              new DictListener(baseMapper)     监听器
              sheet()      工作表，空代表所有
             */
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询id 是否有数据
     */
    private Boolean hadChild(Long id){
        QueryWrapper<Dict> qw = new QueryWrapper<>();

        qw.eq("parent_id", id);

        Integer integer = baseMapper.selectCount(qw);

        return integer>0;
    }
}
